<?php
/**
 * treasure.php 藏宝室
 * Jack能够在该页面中查看到自己处理过的还没有背诵的单词的集合。
 * 它们将以列表的形式呈现，每页现实21个词汇。
 */
require_once 'setting.php';
require_once 'smarty.php';

require_once 'functions.php';
require_once 'paging.php';

require_once INCLUDESPATH . 'db/User.php';
require_once INCLUDESPATH . 'db/UserDAO.php';
require_once INCLUDESPATH . 'db/Word.php';
require_once INCLUDESPATH . 'db/WordDAO.php';

# start the session function
if (!isset($_SESSION)) {
	session_start();
}

# << start - ...
# @todo inbox 验证用户是否已经登陆，未登陆的话跳转到对应的页面，已登陆则继续
if (isset($_SESSION['user'])) {
	$user = $_SESSION['user'];
} else {
	jumpToPage('signin.php?redirect=treasure.php');
}
# >> end - ...

if (isset($_GET['next']) && $_GET['next'] == 'delete') {
	# 删除单词
	if (isset($_GET['id'])) {
		$id = intval($_GET['id']);
		if ($id < 0) {
			$id = 0;
		}
		$worddao = new WordDAO();
		$word = $worddao->retrieveById($id);
		if ($word) {
			if (wordExist($user->getId(), $word->getKey())) {
				$worddao->delete($id);
				$tipmessage = 'Delete word "' . $word->getKey() . '" successfully.';
			} else {
				$tipmessage = 'An error occur!';
			}
		}
	}
	if (isset($_GET['page'])) {
		$page = intval($_GET['page']);
		if ($page <= 0) {
			$page = 1;
		}
	}
	showTreasurePage($page);
} elseif (isset($_GET['page'])) {
	$page = intval($_GET['page']);
	if ($page <= 0) {
		$page = 1;
	}
	showTreasurePage($page);
}else {
	showTreasurePage(1);
}
function showTreasurePage($currentpage, $tipsmsg='') {
	global $pagetitle;
	$smarty = new MySmarty();
	$paging = new PagingWords($currentpage, 'treas');
	$paging->getPagingWords();
	//	echo "<pre>";

	//	print_r($paging);
	//	die();
	# title
	$smarty->assign('title', $pagetitle['treasure']);

	# << start - words list and links
	# words list
	$smarty->assign('wordslist', $paging->getPagingWords());
	# current page number
	$smarty->assign('currentpage', $paging->getCurrentPage());
	# all pages amount
	$smarty->assign('pagesamount', $paging->getPagesAmount());
	# paging links
	$paginglinks = $paging->getPagingLinks();
	foreach ($paginglinks as $key => $value) {
		$smarty->assign($key, $value);
	}
	# >> end - words list and links

	# tips messages
	if ($tipsmsg != '') {
		if (is_array($tipsmsg)) {
			foreach ($tipsmsg as $key => $value) {
				$smarty->assign($key, $value);
			}
		}
	}

	# show page
	$smarty->display('treasure.tpl');
}
?>